<?php


/**
	启动挂起
	nohup   /home/work/php/bin/php   /home/wwwroot/live/server/ws.php  > /home/wwwroot/live/server/ws.log 2>&1
*/

class Http{
	
	// 地址和端口
	CONST HOST = "0.0.0.0";
    CONST PORT = 8811;
	CONST CHAT_PORT = 8812;
	
	// $http 的服务
	public $http = null;
	
	public function __construct() {
		//$this->http = new swoole_http_server(self::HOST, self::PORT);
		$this->http = new swoole_websocket_server(self::HOST, self::PORT);
		
		$this->http->listen(self::HOST,self::CHAT_PORT,SWOOLE_SOCK_TCP);
		
		
        $this->http->set(
            [
                'enable_static_handler' => true,
				'document_root' => "/home/wwwroot/live/public/static/",
                'worker_num' => 2,
                'task_worker_num' => 2,
            ]
        );
		
		$this->http->on("start",[$this,"onStart"]);
		$this->http->on("open",[$this,"onOpen"]);
		$this->http->on("message",[$this,"onMessage"]);
		
		$this->http->on("WorkerStart",[$this,"onWorkerStart"]);
		$this->http->on("request",[$this,"onRequest"]);
		$this->http->on("task",[$this,"onTask"]);
		$this->http->on("finish",[$this,"onFinish"]);
		
		$this->http->on("close",[$this,"onClose"]);
		
		//$this->http->start();
		$this->http->start();
	}
	
	
	public function onStart($serv){
		swoole_set_process_name("live_master");
	}
	
	/**
     * 监听ws连接事件
     * @param $serv
     * @param $request
    */
	 
	public function onOpen($serv, $frame){
		// echo "client number :".$frame->fd;
		
		app\common\lib\Predis::getInstance()->sadd('live_game_key',$frame->fd);
	}
	
	/**
     * 监听ws消息事件
     * @param $serv
     * @param $frame
     */
	public function onMessage($serv, $frame){
		echo "ser-push-message : {$frame->data} \n";
		
		$odata = [
			's'=>1,
			'title'=>" this is server ",
			'content'=>" this is server ",
		];
		
		$serv->push($frame->fd,json_encode($odata));
		
	}
	
	
	//进程启动时发生。 加载 thinkphp 框架
	public function onWorkerStart($server,  $worker_id){
		// 定义应用框架
		define("APP_PATH",__DIR__."/../application/");
		
		// 加载框架里面的文件
		//require __DIR__."/../thinkphp/base.php";
		require __DIR__."/../thinkphp/start.php";
		
	}
	
	
	public function onRequest($request, $response){
		$_SERVER  =  [];
		if(isset($request->server)) {
			foreach($request->server as $k => $v) {
				$_SERVER[strtoupper($k)] = $v;
			}
		}
		if(isset($request->header)) {
			foreach($request->header as $k => $v) {
				$_SERVER[strtoupper($k)] = $v;
			}
		}
		
		$_GET = [];
		if(isset($request->get)) {
			foreach($request->get as $k => $v) {
				$_GET[$k] = $v;
			}
		}
		
		$_POST = [];
		if(isset($request->post)) {
			foreach($request->post as $k => $v) {
				$_POST[$k] = $v;
			}
		}
		
		$this->writeLog();
		$_POST['http_server'] = $this->http;
		
		ob_start();
		try{
			think\App::run()->send();
			
		}catch(\Exception $e){
			// 异常处理
		}
		
		
		$res = ob_get_contents();
		ob_end_clean();
		
		$response->end($res);
		
	}
	
	
	// 多任务，进程
	public function onTask($serv, $taskId, $workerId, $data){
		
		//分发 task 任务机制，让不同的任务 走不同的逻辑
		
		
		$obj = new app\common\lib\Task;
		
		$method = $data['method'];
		
		$flag = $obj->$method($data['data'],$serv);
		
		return $flag;
		
	}
	
	
	
	
	public function onFinish($serv, $taskId, $data){
		 echo "finish-data-sucess:{$data}\n";
		 
	}
	
	public function onClose($serv, $taskId){
		echo "$taskId";
	}
	
	
	public function writeLog(){
		$datas = array_merge(['date'=>date("Y-m-d H:i:s")],$_GET,$_POST,$_SERVER);
		
		$logs = "";
		foreach($datas as $k=>$v){
			$logs = $k." : ".$v.PHP_EOL;			
		}
		
		/**
		echo __DIR__."/Runtime/log/".date("Ym")."/".date("d")."/_access.log";
		
		 
		swoole_async_writefile(__DIR__."/Runtime/log/".date("Ym")."/".date("d")."_access.log",$logs,function($filename){
			
		},FILE_APPEND);
		
		*/
		 
	}
	
}

new Http();


/**

$http = new swoole_http_server('0.0.0.0',8811);


$http->set(
	[
		'enable_static_handler' => true,
        'document_root' => "/home/wwwroot/live/public/static/live",
		'worker_num' => 5,
	]
);

$http->on("WorkerStart",function(swoole_server $server,  $worker_id){
	
	
});



$http->on('request',function($request, $response) use($http){
	
	//$response->cookie('fwz','fengzi',time()+1800);  // 设置cookie
	//$response->end("ssss".json_encode($request->get));
	
	$_SERVER  =  [];
	if(isset($request->server)) {
		foreach($request->server as $k => $v) {
			$_SERVER[strtoupper($k)] = $v;
		}
	}
	if(isset($request->header)) {
		foreach($request->header as $k => $v) {
			$_SERVER[strtoupper($k)] = $v;
		}
	}
	//echo APP_PATH.PHP_EOL;
	
	// print_r($_SERVER);
		
	$_GET = [];
	if(isset($request->get)) {
		foreach($request->get as $k => $v) {
			$_GET[$k] = $v;
		}
	}
	
	$_POST = [];
	if(isset($request->post)) {
		foreach($request->post as $k => $v) {
			$_POST[$k] = $v;
		}
	}
	
	ob_start();
	try{
		think\App::run()->send();
		//think\Container::get('app', [APP_PATH])->run()->send();
		
	}catch(\Exception $e){
		// 异常处理
	}
	
	// echo "--action--".request()->action().PHP_EOL;
	// print_r($_SERVER);
	$res = ob_get_contents();
    ob_end_clean();
	
    $response->end($res);
	
});


$http->start();
 */